﻿@{
    Layout = "_LayoutH";
    @model Sys_user
}
<div id="app" v-cloak>
    <form class="form-horizontal" onsubmit="return false">
        <div class="box-body">
            <table class="table table-bordered">
                <tr>
                    <td colspan="2">
                        <div class="form-group">
                            <label class="col-sm-2 control-label"><span class="c-red">*</span>层级名称：</label>
                            <div class="col-sm-10">
                                <select v-model="DeptId" class="form-control" v-on:change="getClient" v-bind:disabled="DeptId==LoginDeptId">
                                    <option v-for="item in DeptNameList" v-bind:value="item.DeptId" v-text="item.DeptName" v-bind:selected="item.DeptId==DeptId"></option>
                                </select>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="form-group">
                            <label class="col-sm-2 control-label"><span class="c-red">*</span>用户名：</label>
                            <div class="col-sm-10">
                                <input v-model="UserName" type="text" class="form-control" v-focus>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">角色：</label>
                            <div class="col-sm-10">
                                <select class="form-control" v-model="RoleId">
                                    <option value="">请选择</option>
                                    @{
                                        if (ViewBag.Role != null || ViewBag.Role.Count > 0)
                                        {
                                            foreach (var item in ViewBag.Role)
                                            {
                                                <option value="@item.RoleId">@item.RoleName</option>
                                            }
                                        }
                                    }
                                </select>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="form-group" v-if="UserId<=0">
                            <label class="control-label col-sm-2"><span class="c-red">*</span>初始密码：</label>
                            <div class="col-sm-10">
                                <input type="password" class="form-control" autocomplete="off" value="" placeholder="密码" v-model="Pwd1">
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="form-group" v-if="UserId<=0">
                            <label class="control-label col-sm-2"><span class="c-red">*</span>确认密码：</label>
                            <div class=" col-sm-10">
                                <input type="password" class="form-control" autocomplete="off" placeholder="确认新密码" v-model="Pwd2">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="form-group">
                            <label class="control-label col-sm-2">手机：</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" v-model="Tel">
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">邮箱：</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" v-model="Email">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户绑定：</label>
                            <div class="col-sm-10">
                                <select id="ClientId" ref="ClientId" class="form-control" v-model="ClientId" multiple>
                                    <option v-for="item in ClientListRes" v-bind:value="item.ClientId" v-text="item.ClientName"></option>
                                </select>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td style="vertical-align:bottom">
                        <label class="control-label">已绑定的公司：</label>
                    </td>
                    <td style="float:right">
                        <button id="btn_delete" v-on:click="deleteL" type="button" class="btn btn-default">
                            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                        </button>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <table id="bootstraptable"></table>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">备注：</label>
                            <div class="col-sm-10">
                                <textarea v-model="Remark" class="form-control" rows="3" placeholder="备注...100个字符以内"></textarea>
                                <p class="textarea-numberbar"><em class="textarea-length">{{count}}</em>/100</p>
                            </div>
                        </div>
                    </td>
                </tr>
            </table>


            <div class="box-footer">
                <div class="pull-right box-tools">
                    <input v-on:click="addL" class="btn btn-primary radius" type="submit" v-model="submit">
                </div>
            </div>
        </div>
    </form>
</div>
@section scripts{
    <script src="~/js/yui.min.js"></script>
    <script>

        var app = new Vue({
            el: "#app",
            data: {
                submit: "添加",
                sex: "@Model.Sex",
                Remark: "@Model.Remark",
                Tel: "@Model.Tel",
                Email: "@Model.Email",
                UserName: "@Model.UserName",
                Pwd1: "",
                Pwd2: "",
                RoleId: "@Model.RoleId",
                DeptId: "@Model.DeptId",
                UserId: "@Model.UserId",
                DeptNameList: [],
                ClientList:@Html.Raw(ViewBag.Client),
                ClientListRes: [],
                ClientId: [],
                LoginDeptId: "@ViewBag.LoginDeptId",
                LoginUserName:"@ViewBag.LoginUserName"
            },
            computed: {
                count: function () {
                    return this.strLength(this.Remark, false);
                }
            },
            mounted: function () {
                var _self = this;
                _self.$nextTick(function () {
                    _self.loadL();
                    if (_self.UserId > 0) {
                        _self.submit = "修改";
                    }

                    yui.$axiospostform('/Dept/SingleList')
                        .then(function (response) {
                            _self.DeptNameList = [];
                            var result = response.data;

                            result.forEach((item) => {
                                //
                                //登陆用户自己编辑自己时，可以看到本层级
                                if (_self.LoginDeptId == _self.DeptId) {
                                    _self.DeptNameList.push({ DeptId: item.DeptId, ParentId: item.ParentId, DeptNo: item.DeptNo, DeptName: item.DeptName });
                                } else {
                                    //admin有更高权限
                                    if (_self.LoginUserName=="admin") {
                                        _self.DeptNameList.push({ DeptId: item.DeptId, ParentId: item.ParentId, DeptNo: item.DeptNo, DeptName: item.DeptName });
                                    } else {
                                        //不是自己登陆时，只能看到下属层级
                                        if (item.DeptId != _self.LoginDeptId) {
                                            _self.DeptNameList.push({ DeptId: item.DeptId, ParentId: item.ParentId, DeptNo: item.DeptNo, DeptName: item.DeptName });
                                        }
                                    }
                                    
                                }
                            });

                            let listCopy = _self.ClientList.filter(function (data) {
                                return true;
                            });
                            if (_self.DeptId != "") {
                                //获取层级及其所有后代
                                var deptIdResult = [];
                                //将选中的层级添加到数据中
                                deptIdResult.push(_self.DeptId);
                                //将选中层级的后代添加到数据中
                                _self.getAllLevel(_self.DeptNameList, deptIdResult, _self.DeptId);
                                _self.ClientListRes = [];
                                //获取所有DeptId对应的client信息
                                for (let j = 0; j < deptIdResult.length; j++) {
                                    let filterres = listCopy.filter(function (data) {
                                        return data.ParentId == deptIdResult[j];
                                    });
                                    _self.ClientListRes = _self.ClientListRes.concat(filterres);
                                }

                            } else {
                                _self.ClientListRes = listCopy;
                            }
                        })
                        .catch(function (error) {

                        });

                    $("#ClientId").select2();
                });


            },
            methods: {
                loadL() {
                    _self = this;
                    $("#bootstraptable").bootstrapTable({
                        url: "/UserClient/List?userId=" + _self.UserId,
                        method: "GET",
                        pagination: true, //是否显示分页（*）
                        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
                        pageNumber: 1, //初始化加载第一页，默认第一页,并记录
                        pageSize: 5, //每页的记录行数（*）
                        pageList: [5, 10, 20, 'All'], //可供选择的每页的行数（*）
                        columns: [{
                            checkbox: true,             //是否显示复选框
                            visible: true
                        }, {
                            field: 'no',
                            title: '序号',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        }, {
                            field: 'Id',
                            title: 'Id',
                            visible: false
                        }, {
                            field: 'ClientId',
                            title: '公司ID',
                            visible: false
                        }, {
                            field: 'ClientName',
                            title: '公司名称',
                            align: 'center',
                            sortable: true
                        }]
                    });

                },
                addL: function () {
                    var _self = this;
                    if (_self.UserName.length <= 0) {
                        layer.msg("姓名不能为空", { icon: 2 });
                        return false;
                    }
                    if (_self.UserId.length <= 0) {
                        if (_self.Pwd1.length <= 0) {
                            layer.msg("密码不能为空", { icon: 2 });
                            return false;
                        }
                        if (_self.Pwd2 !== _self.Pwd1) {
                            layer.msg("两次输入密码不一致", { icon: 2 });
                            return false;
                        }
                    }
                    //if (_self.DeptNo.length <= 0) {
                    //    layer.msg("请选择层级编号", { icon: 2 });
                    //    return false;
                    //}
                    if (_self.DeptId.length <= 0) {
                        layer.msg("层级名称不能为空", { icon: 2 });
                        return false;
                    }

                    if (_self.RoleId.length <= 0) {
                        layer.msg("请选择角色", { icon: 2 });
                        return false;
                    }
                    var index = layer.load(1, {
                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                    });
                    var selectRes = $('#ClientId').select2('val');
                    var userClient = selectRes.join(',');

                    var data = {
                        id: _self.UserId,
                        UserName: _self.UserName,
                        UserNickname: _self.UserName,
                        Pwd: _self.Pwd2,
                        Remark: _self.Remark,
                        Tel: _self.Tel,
                        RoleId: _self.RoleId,
                        sex: _self.sex,
                        Email: _self.Email,
                        DeptId: _self.DeptId,
                        userClient: userClient

                    };
                    yui.$axiospostform('/User/AddOrUpdate', data)
                        .then(function (response) {
                            if (response.data.Item1 === 101) {
                                layer.tips(response.data.Item2, '.layui-layer-setwin', {
                                    tips: [1, '#3595CC'],
                                    time: 3000
                                });
                                layer.close(index);
                                return false;
                            }
                            if (response.data.Item1) {
                                layer.msg(response.data.Item2, { icon: 1, time: 1000 });
                                setTimeout(function () {
                                    yui.layer_close3();
                                }, 500);
                            } else {
                                layer.msg(response.data.Item2, { icon: 5 });
                            }
                            layer.close(index);
                            parent.app.searchL();
                        })
                        .catch(function (error) {
                            layer.close(index);
                        });
                },
                deleteL() {
                    _self = this;
                    var arr = $("#bootstraptable").bootstrapTable('getSelections');
                    if (arr.length > 0) {
                        var index = layer.confirm("您确定要删除吗？", { btn: ["确定", "取消"] }, function () {
                            var id = arr[0].Id;
                            yui.$axiosget('/UserClient/Delete?id=' + id)
                                .then(function (response) {
                                    if (response.data.Item1) {
                                        layer.msg(response.data.Item2 || errorMsg, { icon: 1 });
                                        $("#bootstraptable").bootstrapTable("refresh");
                                    } else {
                                        layer.msg(response.data.Item2 || errorMsg, { icon: 5 });
                                    }
                                })
                                .catch(function (error) {
                                    layer.msg(error.message, { icon: 5 });
                                });
                            layer.close(index);
                        });
                    } else {
                        layer.alert("请选中行", { icoon: 3, skin: "layer-ext-moon" });
                    }
                },
                getClient() {
                    let _self = this;

                    let listCopy = _self.ClientList.filter(function (data) {
                        return true;
                    });
                    //获取选择的层级信息（有且只有一笔数据）
                    let deptList = _self.DeptNameList.filter(function (data) {
                        return data.DeptId == _self.DeptId;
                    });
                    //所选择的层级
                    let res = listCopy.filter(function (data) {
                        return data.ParentId == _self.DeptId && deptList[0].DeptName == "管理员";
                    });
                    //如果是管理员，则能看到所有客户
                    if (res.length > 0) {
                        _self.ClientListRes = listCopy;
                    } else {
                        //获取层级及其所有后代
                        var deptIdResult = [];
                        //将选中的层级添加到数据中
                        deptIdResult.push(_self.DeptId);
                        //将选中层级的后代添加到数据中
                        _self.getAllLevel(_self.DeptNameList, deptIdResult, _self.DeptId);
                        _self.ClientListRes = [];
                        //获取所有DeptId对应的client信息
                        for (let j = 0; j < deptIdResult.length; j++) {
                            let filterres = listCopy.filter(function (data) {
                                return data.ParentId == deptIdResult[j];
                            });
                            _self.ClientListRes=_self.ClientListRes.concat(filterres);
                        }
                    }
                    //加上此下拉框才会更新
                    $("#ClientId").select2();
                },
                //递归
                getAllLevel(source, deptIdResult, deptId) {
                    let res = source.filter(function (data) {
                        return data.ParentId == deptId;
                    });

                    if (res.length > 0) {
                        for (let i = 0; i < res.length; i++) {
                            deptIdResult.push(res[i].DeptId);
                            this.getAllLevel(source, deptIdResult, res[i].DeptId);
                        }

                    }
                }
            }
        })
    </script>
}